package eightDataType.mStr;

/**
 * @author Ajie
 * @date 2022/11/21
 * @function  String的intern方法
 *
 * String.intern()方法主要适用于程序中需要保存
 * 有限个会被反复使用的值的场景，这样可以减少内存消耗，
 * 同时在进行比较操作时减少时耗，提高程序性能。
 * 1. 有限个 String
 * 2.重复使用 减少内存 or 比较 提高性能。
 */
public class StringIntern {

    public static void main(String[] args) {

        System.err.println("java.version:"+System.getProperty("java.version"));//1.8.0_221

        intern2();


//        String name = "demo";
//        String type = "demo";
//        String newName = new String ("demo");
//        System.out.println("name == type:"+(name == type));//true
//        System.out.println("name == newName:"+(name == newName));//false
//        String internedState = newName.intern();
//        System.out.println("name == internedState:"+(name == internedState));//true
//
//        newName = null;
//        System.out.println("StringIntern:main:"+internedState);
//        System.out.println("name == internedState 2:"+(name == internedState));//true

    }

    private static void intern2() {
        String hello = new String ("hello");//堆中  false
//        String hello = new String("he")+new String("llo");//堆中 true
//        String hello = "he"+"llo";//堆中 true
        hello.intern();

        String helloField = "hello";
        System.out.println("hello == helloField:"+(hello == helloField));

        String world = "world";//true
        String worldField = "world";
        System.out.println("world==worldField:"+(world==worldField));//true


        //String newName = new String ("demo");//false
        String newName = new String ("de")+new String("mo");//true
        String internedState = newName.intern();

        String name = "demo";
        //TODO new String ("demo") false,,,  "de"+"mo" true
        System.out.println("name == newName:"+(name == newName));

        System.out.println("name == internedState:"+(name == internedState));//alway true

    }

}
